<?php
namespace Home\Controller;

use My\Model\DistributionShopOrderModel;
use My\Model\WechatUserModel;
use Utuo\DistributionShopOrderController;

class DisShopGiftsOrderController extends DistributionShopOrderController {
	
	/**
	 * 我的订单
	 */
	public function listAction() {
		$type = I ( "type" );
		$m = M ( "DistributionShopOrder orders" );
		$condition = array (
				"orders.uid" => $this->uid,
				"orders.buy_method" => DistributionShopOrderModel::BUY_METHOD_GIFTS,
		);
	
		if ( $type == 1 ) { // 我的送礼 
			
		} elseif( $type == 2 ) { // 我的收礼
			unset($condition['orders.uid']);
			/* 送礼订单 */
			$m->join ( "__DISTRIBUTION_SHOP_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" );
			$condition['gifts.to_uid'] = $this->uid;
		}
		$orderLists = $m->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
							->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
							->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
							->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
							->where ( $condition )->order("orders.id desc")->select ();
		$this->bindOrderDetail ( $orderLists );
		$this->assign("types", \My\Model\DistributionShopOrderModel::$TYPES);
		$this->assign ( "orderLists", $orderLists );
		$this->display ( "{$this->modelControllerName}/giftsOrderList" );
	}
	
	
	/**
	 * 订单结算页
	 */
	public function confirmOrderAction() {
		$orderId = I('orderId', 0, "intval");
		$order = array();
		if ( $orderId ) {
			$order = $this->getPayingOrder( $orderId );
		} else {
			$order = $this->getSaveingOrder();
			session ( "order", $order );
		}
		$this->assign ( "orderJSON", json_encode ( $order ) );
		$this->assign ( 'order', $order );
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->display ( "{$this->modelControllerName}/" .ACTION_NAME."Gifts" );
	}
	
	/**
	 * 获得已保存欲支付订单
	 * @return array 格式参考getSaveingOrder
	 */
	protected function getPayingOrder( $id ) {
		$addressId = I('addressId', 0, "intval");
		$order = $this->getOrder($id);
		if ( $order ) {
			// 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口)
			$produtPayApiLists = $this->getPayApiList();
			/* 转化为确认订单可显示的格式 */
			$order['createTime'] = $order['create_time'];
			$order['orderNo'] = $order['order_id'];
			$order['totalPrice'] = sprintf("%.2f", $order['goods_amount'] + $order['shipping_fee']);
			$order['goodsTotalPrice'] = $order['goods_amount'];
			$order['shippingTotalPrice'] = $order['shipping_fee'];
			$order['productPayApiOptions'] =  $this->getOption( $produtPayApiLists );
			foreach ( explode(',', "create_time,order_id,goods_amount,shipping_fee,consignee,province,city,area,tel") as $v ) {
				unset($order[$v]);
			}
			foreach ( $order['orderItems'] as $productId => &$productItems ) {
				$productItems['name'] = $productItems['productName'];
				foreach ( $productItems['items'] as $businessId => &$items) {
					$items['quantity'] = $items['productNumber'];
					$items['attrs'] = $items['productAttr'];
					$items['pic'] = $items['productPic'];
					unset($items['productNumber']);
					unset($items['productAttr']);
					unset($items['productPic']);
					unset($items['rate_status']);
				}
				unset($productItems['productName']);
			}
			return $order;
		}
	}
	
	/**
	 * 获得欲保存订单
	 * @return
	 * array(
	 *  ["atOnce"] => int(1)
	 *  ["createTime"] => int(1417767435)
	 *  ["orderNo"] => string(22) "1412051617150000011771"
	 *  ["totalPrice"] => float(138)
	 *  ["goodsTotalPrice"] => float(138)
	 *  ["shippingTotalPrice"] => float(0)
	 *  ["productPayApiOptions"] => string(46) "<option value='WxTenpay'>微信支付</option>"
	 *  ["orderItems"] => array(1) {
	 *  ["8"] => &array(4) {
	 *    ["productId"] => string(1) "8"
	 *    ["name"] => string(26) "阿芙薰衣草精油10ml "
	 *    ["support_cod"] => string(1) "0"
	 *    ["items"] => array(1) {
	 *      ["b123198bb0678beddc453e07c57bbc48c8141776743580"] => &array(5) {
	 *        ["businessId"] => string(46) "b123198bb0678beddc453e07c57bbc48c8141776743580"
	 *        ["productPrice"] => string(6) "138.00"
	 *        ["quantity"] => int(1)
	 *        ["attrs"] => NULL
	 *        ["pic"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-11-14/2014111411424640164318.jpg"
	 *      }
	 *    }
	 *  }
	 * }
	 * ["supportCod"] => int(0)
	 * ["address"] => array(13) {
	 *   ["id"] => string(1) "1"
	 *   ["uid"] => string(2) "29"
	 *   ["name"] => string(6) "宋义"
	 *   ["province"] => string(6) "230000"
	 *   ["city"] => string(6) "230200"
	 *   ["area"] => string(6) "230204"
	 *   ["zipcode"] => string(0) ""
	 *   ["address"] => string(15) "ewqrewqrewqrewq"
	 *   ["tel"] => string(11) "13849089206"
	 *   ["status"] => string(1) "1"
	 *   ["provinceName"] => string(12) "黑龙江省"
	 *   ["cityName"] => string(15) "齐齐哈尔市"
	 *   ["areaName"] => string(9) "铁锋区"
	 * }
	 * )
	 */
	protected function getSaveingOrder() {
		$order = array();
		$d = D ( "My/DistributionShopGoods", "Model" );
		$items = $this->getItems(); // 获得要结算的商品
		$totalPrice = 0; // 总价
		foreach ( $items ["items"] as &$v ) {
			$count = 0; // 购买数量
			$subtotal = 0; // 小计
			/* 处理显示属性可看 */
			foreach ( $v ['items'] as &$v0 ) {
				$count += $v0 ['quantity'];
				$subtotal += $v0 ['productPrice'] * $v0 ['quantity'];
			}
			$totalPrice += $subtotal;
			/* 计算运费 */
			$shippingPrice = $d->getShipping ( $v['productId'], $count );
			$totalShpping += $shippingPrice;
		}
	
		// 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口)
		$produtPayApiLists = $this->getPayApiList();
		
		$order = array (
				'atOnce' => $items ["atOnce"],
				'buyMethod' => DistributionShopOrderModel::BUY_METHOD_GIFTS, // 购买方式
				'createTime' => time (),
				'orderNo' => DistributionShopOrderModel::randOrderNo($this->sid), // 订单号
				'totalPrice' => $totalPrice + $totalShpping,
				'goodsTotalPrice' => $totalPrice,
				'shippingTotalPrice' => $totalShpping, // 配送方式数据(确认订单,更改地址时使用)
				'productPayApiOptions' => $this->getOption( $produtPayApiLists ),
				'orderItems' => $items ["items"],
				'supportCod' => 0,
		);
	
		return $order;
	}
	
	/**
	 * 提交送礼订单
	 */
	public function confirmOrderPostAction() {
		$orderId = I('orderId', 0, "intval"); // 订单id
		$orderNo = I ( 'orderNo', 0 ); // 订单单号
		$payApitype = I("apitype", "");
		if ( !$orderId ) {
			$orderId = $this->addOrder($orderNo, $payApitype);
		} else {
			/** 更新订单 */
		}
		/*支付转入*/
		if ( empty($payApitype) ) {
			$order = $this->getOrder ( $orderId );
			$this->assign ( "order", $order );
			$this->display ( "{$this->modelControllerName}/showOrder" );
		} else {
			redirect($this->getPayUrl(array(
				'id' => $orderId,
				'sid' => $this->cid,
				'apitype' => $payApitype,
			)));
		}
		exit ();
	}
	
	/**
	 * 添加订单
	 */
	public function addOrder( $orderNo, $payApitype ) {
		$order = session ( "order" ); // 要保存的订单
		$addressLists = $order ['addressLists'];
		
		/* 购买时的代理商  */
// 		$aid = $this->getAid(); // 代理商id
// 		if ( $this->uid == $aid ) {
// 			$aid = 0;
// 		}
		
		/* 获得订单 */
		if ( !$order || $order ['orderNo'] !== $orderNo ) {
			$orderSaved = M("DistributionShopOrder")->where(array( 'order_id'=>$orderNo, 'cid'=>$this->cid) )->find();
			if ( $orderSaved ) { // 订单已存在时
				$this->error ( "订单($orderNo)已超时,正在转向订单详细重新结算.",  U('DisShopOrder/showOrder', "id={$orderSaved['id']}&sid={$this->cid}"));
			} elseif ( !$order || $order and (time () - $order ["createTime"]) > 3 * 60 ) { // 下单超时
				$this->error ( "订单($orderNo){$order ['orderNo']}已超时,正在转向购物车重新结算.",  $this->getCartUrl());
			}
		}
	
		/* 是否支持货到付款 */
		if( $payApitype == "COD" ) {
			if ( !$order['supportCod'] ) {
				$this->error ( "当前订单不支持货到付款" );
			}
		}
	
		/* 获得收货地址 */
		/*$deliverAddress = $this->getAddress();
		$deliverAddress or $this->error ( "没有找到默认的收货地址" );*/
	
		/* 送费 */
		$shippingTotalPrice = $order ['shippingTotalPrice']; // 配送信息
	
		/* 保存订单 */
		$orderData = array (
				'order_id' => $orderNo,
				'cid' => $this->cart->getCid(),
				'uid' => $this->cart->getUid (),
				'agent_id' => $aid*1, // 支持代理模式
				'shipping_fee' => $shippingTotalPrice,
				'goods_amount' => $order ['goodsTotalPrice'],
				'order_status' => DistributionShopOrderModel::ORDER_STATUS_PAY,
				'create_time' => $order ['createTime'],
				'confirm_time' => 0,
				'shipping_time' => 0,
				'support_cod' => $order['supportCod'],
		);
		
		/* 送礼订单数据 */
		$orderData = array_merge($orderData, array(
				'buy_method' => DistributionShopOrderModel::BUY_METHOD_GIFTS,
				'consignee' => '',
				'province' => '',
				'city' => '',
				'area' => '',
				'address' => '',
				'zipcode' => '',
				'tel' => '',
				'express_name' => '',
		));
		
		$offset = 0; // 抵消金额
		
		/* 使用的优惠卷 */
		$packetCode = I('packetCode', '');
		$packetCode and ( $redPacket = M("DistributionShopRedPacket")->where(array('uid'=>$this->uid, 'code'=>$packetCode, 'efficacy'=>1))->find() or $this->error ( "您选择了无效的优惠卷" ) );
		if ( $redPacket ) {
			$orderData['red_packet_offset'] = $offset = $redPacket['value'];
			$orderData['red_packet_id'] = $redPacket['id']*1;
		}
		
		/* 实际消费总额 */
		$orderData['actual_cost'] = $order ['goodsTotalPrice'] + $shippingTotalPrice - $offset;
	
		$d = D ( "DistributionShopOrder" );
		if ( $orderId = $d->add ( $orderData ) ) {
			// 添加送礼订单
			M("DistributionShopGifts")->add(array(
				'order_id' => $orderId,
				'uid' => $this->uid,
				'to_uid' => 0,
				'buy_status' => DistributionShopOrderModel::ORDER_GIFTS_STATUS_SAVED,
			));
			// 添加所有订单商品
			$m = M ( "DistributionShopOrderGoods" );
			$goodsList = $this->getOrderGoods( $order['orderItems'], $orderId);
			if ( false != $m->addAll ( $goodsList ) ) {
				$order ['atOnce'] or $this->cart->clearAll ();
				session ( "order", null );
				/*更新订单总佣金*/
				$baseRewards = DistributionShopOrderModel::calcRewardBonus($goodsList);
				$dealerRewards = DistributionShopOrderModel::calcRewardBonusDealer($goodsList);
				$baseBonus = array_sum(array_values($baseRewards['totalUser']));
				$dealerBonus = array_sum(array_values($dealerRewards['totalUser']));
				$d->where('id=%d', $orderId)->save(array(
						'total_bonus' => $baseRewards['orderBonus'] + $dealerRewards['orderBonus'],
						'reward_uids' => join(',', array_keys($baseRewards['totalUser'])),
						'reward_bonus' => join(',', array_values($baseRewards['totalUser'])),
						'reward_uids_dealer' => join(',', array_keys($dealerRewards['totalUser'])),
						'reward_bonus_dealer' => join(',', array_values($dealerRewards['totalUser'])),
						'surplus' => $order ['goodsTotalPrice'] - ($baseRewards['orderBonus'] + $dealerRewards['orderBonus']), // 盈余 = 订单总额 - ( 基础分成总额 + 特约经销商分成总额  )
				));
				sleep(5);
				return $orderId;
			} else {
				$d->where ( "id=%d", $orderId )->setField ( "order_status", DistributionShopOrderModel::ORDER_STATUS_INVALID );
			}
		}
		$this->error ( '订单保存错误.' );
	}
	
	
	/**
	 * 确认收货
	 */
	public function signInAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "DistributionShopOrder" );
		$order = $this->getOrder( $orderId );
		if ( $order['to_uid'] != $this->uid ) {
			$this->ajaxError( "此订单不属于您不能签收" );
		}
		if( $order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN ) {
			// 更新订单状态
			$data = array("order_status" => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
						"take_time" => time(),
						"deal_time" => time(),);
			if( false !== $d->where ( array ( "id" => $orderId, ) )
							->save ( $data ) ) {
						$order = array_merge($order, $data);
						$this->afterOrderCompleted( $order );
						$this->ajaxSuccess ( "已签收" );
			}
		} else {
			$this->ajaxError ( "非已发货状态，不能完成收货操作。" );
		}
		$this->ajaxError ( "提交失败，请重新确认收货" );
	}
	
	/**
	 * 抢礼
	 */
	public function receiveGiftsAction() {
		$id = I ( "id", 0, "intval" );
		$order = $this->getOrder ( $id );
		$order['operates'] = $this->getOrderOperate( $order );
		
		/* 获得用户默认收货地址 */
		$address = M ( "DistributionShopDeliverAddress address" )->join ( "__CN_PROVINCE__ province on address.province = province.code", "LEFT" )->join ( "__CN_CITY__ city on address.city = city.code", "LEFT" )->join ( "__CN_AREA__ area on address.area = area.code", "LEFT" )->field ( "address.*,province.name as provinceName, city.name as cityName, area.name as areaName" )->where ( "address.uid=%d", $this->uid )->order ( "address.status desc" )->find ();
		if ( $address ) {
			if ( !$address['status']*1 ) {
				M ( "DistributionShopDeliverAddress" )->where(array('uid' => $this->uid))->save(array('status' => array('exp', "CASE id WHEN $id THEN 1 ELSE 0 END")));
			}
			$order ['address'] = $address;
		}
		
		/* 回调url */
		$this->assign("buyUrl", urlencode($this->getCurrentUrl()));
		
		$this->assign ( "order", $order );
		$this->display ( "{$this->modelControllerName}/".ACTION_NAME );
	}
	
	/**
	 * 确认抢礼
	 */
	public function receiveGiftsPostAction() {
		$msg = "网络错误请重试";
		$id = I("id", 0, "intval");
		$addressId = I('addressId', 0, "intval");
		$key = "rg{$this->cid}-{$id}";
		$order = $this->getOrder ( $id ) or $this->error("订单已不存在了~");
		if ( $order['buy_method'] != DistributionShopOrderModel::BUY_METHOD_GIFTS  ) {
			$this->error("参数错误,确认的订单不是收礼订单~");
		}
		$address = M ( "DistributionShopDeliverAddress address" )->where("address.id=%d and address.uid=%d", $addressId, $this->uid)->find() or $this->error("选择的地址不存在");

		if ( S($key) or $order['buy_status'] == DistributionShopOrderModel::ORDER_GIFTS_STATUS_CONSIGNEE ) {
			$msg = "礼品已被人抢走了~";
		} else {
			S($key, $this->uid);
			$rowCount = M("DistributionShopGifts")->where(array('order_id' => $id,
					'uid' => $order['uid'],
					'buy_status' => DistributionShopOrderModel::ORDER_GIFTS_STATUS_SHARING ))
					->save(array('buy_status' => DistributionShopOrderModel::ORDER_GIFTS_STATUS_CONSIGNEE, 'to_uid' => $this->uid, ));
			if ( false !== $rowCount ) {
				if ( $rowCount ) {
					M("DistributionShopOrder")->where(array(
						'id' => $order['id'],
						'uid' => $order['uid'],
					))->save(array(
						'consignee' => $address['name'],
						'province' => $address['province'],
						'city' => $address['city'],
						'area' => $address['area'],
						'address' => $address['address'],
						'zipcode' => $address['zipcode'],
						'tel' => $address['tel'],
					));
				}
				$msg = "恭喜，您已抢到礼品等待收货吧~";
			}
		}
		header("Content-Type:text/html;charset=utf-8");
		echo "<style>body{font-family: \"Microsoft YaHei\"; font-size: 3em; }</style>";
		redirect(U('Home/DisShop/my', array('sid'=>$this->cid)), 5, $msg);	
	}
	
	
	/**
	 * 订单详细
	 */
	public function showOrderAction() {
		$id = I ( "id", 0, "intval" );
		$order = $this->getOrder ( $id );
		$order['operates'] = $this->getOrderOperate( $order );
		if ( in_array('pay', $order['operates'] ) ) {
			redirect(U('DisShopGiftsOrder/confirmOrder', array('sid'=>$this->cid, 'orderId'=>$id)));
		} elseif ( in_array('share', $order['operates']) ) {
			$orderItemFirst = current($order['orderItems']);
			$this->setShare(array(
					'link' => U('DisShopGiftsOrder/receiveGifts', array('id' => $id, 'sid' => $this->cid ), false, true),
					'img' => $orderItemFirst['items'][0]['productPic'],
					'title' => '您的朋友"'.$this->user['nickname'].'"撒礼物了快来抢啊~~',
					'desc' => $orderItemFirst['productName'],
			));
		}
		$this->assign ( "order", $order );
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->display ( "{$this->modelControllerName}/showGiftsOrder" );
	}
	
}